﻿using System;
using System.Security.Cryptography;

namespace DoNet.Utils
{
    public class StringHelper
    {
        /// <summary>
        /// 生成随机串，随机串包含字母或数字
        /// </summary>
        /// <returns>随机串</returns>
        public static string GenerateNonceStr()
        {
            RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();

            byte[] buffer = new byte[sizeof(uint)];
            csp.GetBytes(buffer);

            return BitConverter.ToUInt32(buffer, 0).ToString();
        }

        /// <summary>
        /// 随机数字字符串
        /// </summary>
        /// <param name="length">字符串长度</param>
        /// <returns></returns>
        public static string GetRandomNumber(int length)
        {
            string code = string.Empty;

            char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            byte[] buffer = Guid.NewGuid().ToByteArray();
            int iSeed = BitConverter.ToInt32(buffer, 0);
            Random random = new Random(iSeed);

            for (int i = 0; i < length; i++)
            {
                code += chars[random.Next(0, 10)].ToString();
            }

            return code;
        }

        /// <summary>
        /// 生成商户订单号
        /// 根据当前系统时间加随机序列来生成订单号
        /// 前缀（WX） + 时间（年月日时分秒毫秒） + 3位随机数
        /// </summary>
        /// <param name="prefix">前缀 微信：WX 支付宝：</param>
        /// <param name="length">随机数长度 默认为3位</param>
        /// <returns></returns>
        public static string GetOutTradeNo(string prefix, string pay_mch, int length = 3)
        {
            var dateStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            var randomNumber = GetRandomNumber(length);
            return string.Format("{0}{1}{2}{3}", prefix, pay_mch, dateStr, randomNumber);
        }
    }
}
